package cn.tedu.medicalpath.base.exception;

import cn.tedu.medicalpath.base.response.JsonResult;
import cn.tedu.medicalpath.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleServiceException(ServiceException e){
        log.error("ServiceException：{}",e.getStatusCode().getMessage());
        return new JsonResult(e.getStatusCode());
    }

    //校验POJO类属性时,参数未满足要求
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        //Objects.requireNonNull()避免空指针异常
        String message = Objects.requireNonNull(e.getFieldError()).getDefaultMessage();
        log.error("MethodArgumentNotValidException：{}",message);
        return new JsonResult(StatusCode.VALIDATE_FAILED,message);
    }

    //声明参数方式接收数据校验时,参数未满足要求
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String message = e.getMessage().substring(e.getMessage().indexOf(":")+1).trim();
        log.error("ConstraintViolationException：{}",message);
        return new JsonResult(StatusCode.VALIDATE_FAILED,message);
    }

    @ExceptionHandler
    public JsonResult doHandleException(Exception e){
        log.error("Exception：{}",e.getMessage());
        return new JsonResult(StatusCode.FAILED,e.getMessage());
    }
}
